import request from "@/utils/request";
import { v4 as uuidv4 } from "uuid";

const state = {
  companyTree: [],
  selectId: "-1", // 选中的公司或者公司组，或者租户的id
  selectName: undefined, // 选中的公司或者公司组，或者租户的名称
  selectType: undefined, // 选中的公司或者公司组，或者租户的类型
  selectAllIds: undefined,
  currentItems: getCurrentItems(),
  groupTree: [],
  groupTreeWithCompany: [],
  companyTreeWithUuid: [],
  companyUuidDict: {},
  companyUuidDictWithInfo: {},
  socConfirm: false
};

const mutations = {
  updateSocConfirm(state, payload) {
    state.socConfirm = payload;
  },
  updateGroupTree(state, payload) {
    state.groupTree = payload;
  },
  updateGroupTreeWithCompany(state, payload) {
    state.groupTreeWithCompany = payload;
  },
  updateCompanyTree(state, payload) {
    state.companyTreeWithUuid = payload.resList;
    state.companyUuidDict = payload.resDict;
    state.companyUuidDictWithInfo = payload.resDictWithInfo;
  },
  updateSelected(state, payload) {
    try {
      Object.keys(payload).forEach((key) => {
        state[key] = payload[key];
      });
    } catch (err) {
      console.log("updateSelected", err);
    }
  },
  updateCurrentItems(state, newItem) {
    let temp = state.currentItems ? [...state.currentItems] : [];
    const oldIdx = temp.findIndex((item) => item.id === newItem.id);
    if (oldIdx > -1) {
      temp.splice(oldIdx, 1);
    }
    temp.unshift(newItem);
    temp = temp.slice(0, 3);
    state.currentItems = temp;
    localStorage.setItem("site_currentItems", JSON.stringify(state.currentItems));
  },
  initCurrentItems(state, companyList) {
    if (companyList && companyList.length > 0) {
      const tempList = JSON.parse(JSON.stringify(companyList));
      if (state.currentItems && state.currentItems.length > 0) {
        let newList = [];
        for (let i = 0; i < state.currentItems.length; i++) {
          const entry = state.currentItems[i];
          const theIdx = tempList.findIndex((item) => item.id === entry.id);
          if (theIdx > -1) {
            newList.push(entry);
            tempList.splice(theIdx, 1);
          }
        }
        const spaceLen = 3 - newList.length;
        newList = newList.concat(tempList.slice(0, spaceLen));
        state.currentItems = newList;
      } else {
        state.currentItems = companyList.slice(0, 3);
      }
    } else {
      state.currentItems = [];
    }
    localStorage.setItem("site_currentItems", JSON.stringify(state.currentItems));
  },
  reload(state) {
    localStorage.setItem("site_currentItems", JSON.stringify(state.currentItems));
  }
};

const actions = {
  checkSocAct({ commit }) {
    request({
      url: `hr/api/v1/empSocPlans/confirmSocBySite`
    })
      .then((res) => {
        commit("updateSocConfirm", res.data === "是");
      })
      .catch((err) => {
        console.log("confirmSocBySite", err);
      });
  },
  updateCurrentItemsAct({ commit, rootState }) {
    commit("updateCurrentItems", {
      id: rootState.hr.companyId,
      name: rootState.hr.companyName
    });
  },
  async loadGroupTreeAct({ commit }) {
    const treeData = await request({
      url: `/hr/api/v1/childrenCompany/tree`,
      method: "get"
    })
      .then((res) => {
        return res.data;
      })
      .catch((err) => {
        console.log(err);
        return false;
      });
    if (treeData) {
      commit("updateGroupTree", treeData);
    } else {
      commit("updateGroupTree", []);
    }
  },
  async loadGroupTreeWithCompanyAct({ commit }) {
    const formattedData = await request({
      url: `/hr/api/v1/childrenCompany/listAll`,
      method: "get"
    })
      .then((res) => {
        return [transGC2G(res.data), formatCompanyUuidTree(res.data)];
      })
      .catch((err) => {
        console.log(err);
        return false;
      });
    if (formattedData) {
      commit("updateGroupTreeWithCompany", formattedData[0]);
      commit("updateCompanyTree", formattedData[1]);
    } else {
      commit("updateGroupTreeWithCompany", []);
    }
  }
};

const getters = {
  // 管理后台
  SelectedId: (state) => state.selectId, // 选中的公司或者公司组，或者租户的id
  CompanyTree: (state) => state.companyTree, // 当前租户下的公司树的数据
  SelectedName: (state) => state.selectName, // 当前选中的名字（可能是租户名，可能是组名，可能是公司名）
  SelectedAllIds: (state) => state.selectAllIds // 当前选中的租户或者公司组下所有的公司id
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
};

function getCurrentItems() {
  const ls = localStorage.getItem("site_currentItems");
  if (ls) {
    return JSON.parse(ls);
  }
  return [];
}

function transGC2G(list) {
  const res = [];
  for (let i = 0; i < list.length; i++) {
    const item = list[i];
    if (item.type === "site" || item.type === "group") {
      const newItem = {
        ...item,
        companyList: transGC2G(item.companyList)
      };
      res.push(newItem);
    }
  }
  return res;
}

function formatCompanyUuidTree(list) {
  if (!list) {
    return {
      resList: [],
      resDict: {},
      resDictWithInfo: {}
    };
  }
  const res = [];
  let dict = {};
  let dictWithInfo = {};
  for (let i = 0; i < list.length; i++) {
    const item = list[i];
    const uuid = uuidv4();
    dict[uuid] = item.id;
    dictWithInfo[uuid] = {
      uuid,
      id: item.id,
      type: item.type,
      name: item.name
    };
    const { resList, resDict, resDictWithInfo } = formatCompanyUuidTree(item.companyList);

    const newItem = {
      ...item,
      uuid: uuid,
      companyList: resList
    };
    dict = {
      ...dict,
      ...resDict
    };
    dictWithInfo = {
      ...dictWithInfo,
      ...resDictWithInfo
    };

    res.push(newItem);
  }
  return {
    resList: res,
    resDict: dict,
    resDictWithInfo: dictWithInfo
  };
}
